'use client'

import React, { useEffect, useRef } from 'react'

const AMapLoader = (window) => {
  return new Promise((resolve, reject) => {
    if (typeof window.AMap !== 'undefined') {
      resolve(window.AMap)
      return
    }
    const script = document.createElement('script')
    script.src = `https://webapi.amap.com/maps?v=2.0&key=946ce5ae8b6fb8bfcd4b8d6065476944&plugin=AMap.Marker`
    script.async = true
    script.onload = () => {
      if (window.AMap) {
        resolve(window.AMap)
      } else {
        reject(new Error('AMap failed to load'))
      }
    }
    script.onerror = () => reject(new Error('AMap script load error'))
    document.head.appendChild(script)
  })
}

export default function Map({ className, zoom = 16, center = [113.704514, 34.774198], positions }) {
  const mapRef = useRef(null);
  useEffect(() => {
    AMapLoader(window).then((AMap) => {
      const map = new AMap.Map(mapRef.current, { center, zoom })
      positions.length > 0 && positions.forEach(({ title, position, content }) => {
        const marker = new AMap.Marker({ position, title });
        map.add(marker);
        if (content) {
          const infoWindow = new AMap.InfoWindow({ content, offset: new AMap.Pixel(0, -30) });
          marker.on('click', () => { infoWindow.open(map, marker.getPosition()) });
        }
      });
      if (window.innerWidth <= 768) { map.panBy(0, -150); }
    })
  }, [ positions, center, zoom]);

  return <div ref={mapRef} className={`w-full min-h-[600px] ${className}`} />
}
